package com.doyens.gmall.product.controller;

import com.doyens.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("admin/product")
public class FileUploadController {

    @Value("${fileServer.url}")
    private String fileUrl;

    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) throws MyException, IOException {
        //读取配置文件、获取仓管的地址信息
        String configFile = this.getClass().getResource("/tracker.conf").getFile();
        String path = null;
        if (configFile != null) {
            ClientGlobal.init(configFile);
            //trackerClient客户端
            TrackerClient trackerClient = new TrackerClient();
            //trackerServer 库管对象
            TrackerServer trackerServer = trackerClient.getConnection();
            //通过库管对象，获取仓库信息
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, null);
            //获取文件信息
            byte[] bytes = file.getBytes();
            //获取文件的原始名称 （abc.jpg）
            String originalFilename = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFilename);
            //上传文件,返回文件的路径
            path = storageClient1.upload_appender_file1(bytes, extension, null);
        }
        return Result.ok(fileUrl + path);
    }
}
